package cn.linweijian.kafka.producerdemo.service;

import cn.linweijian.kafka.producerdemo.common.KafkaMesConstant;
import cn.linweijian.kafka.producerdemo.common.ResponseResult;
import cn.linweijian.kafka.producerdemo.dto.*;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * Description: kafkademo
 * <p>
 * Created by linweijian on 2018/6/4 14:54
 */
@Component
@Slf4j
public class PushTaskService {
    private Gson gson = new GsonBuilder().create();
    @Autowired
    private TaskService taskService;
    @Autowired
    private KafkaProducerServer kafkaProducerServer;

    public ResponseResult pushTask(TaskResult result) {
        try {
            List<TaskDto> insertTask = result.getInserttasks();
            List<TaskDto> updateTask = result.getUpdatetasks();
            TaskResultAfter taskResultAfter = new TaskResultAfter();
            if (insertTask != null && insertTask.size() > 0) {
                List<InsertTaskDto> insertTaskDtos = taskService.insertTask(insertTask);
                taskResultAfter.setInserttasks(insertTaskDtos);
            }
            if (updateTask != null && updateTask.size() > 0) {
                List<UpdateTaskDto> updateTaskDtos = taskService.updateTask(updateTask);
                taskResultAfter.setUpdatetasks(updateTaskDtos);
            }
            //转换
            Map<String, Object> map = kafkaProducerServer.sendMessage("zhuti1", taskResultAfter, false, 1, "test");
            log.info(map.toString());
            String code = (String) map.get("code");
            if (code.equals(KafkaMesConstant.SUCCESS_CODE)) {
                return ResponseResult.success("");
            } else {
                return ResponseResult.error((String) map.get("message"));
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("数据转换失败");
        }
    }

}
